
<!--用户管理界面。应当注意修改路由配置，让首页可以重定向至此-->
<template>
  <el-main>
    <div>
      <!--    顶部搜索栏起-->
      <el-card id="search">
        <el-input v-model="searchModel.userName" placeholder="请输入用户名" />
        <el-input v-model="searchModel.sno" placeholder="请输入学号" />
        <el-button type="primary" round icon="el-icon-search">查询</el-button>

        <!--      当前用户为超级管理员时，显示新增管理员以及切换用户页面按钮，由变量superAdmin控制-->
        <el-button v-if="superAdmin && switchName === '管理员'" type="primary" @click="openEditUI(null, null)" round icon="el-icon-plus">
          新增
        </el-button>

        <!--      switchName为当前页面显示的用户类型，点击即可切换，逻辑实现在switching函数中-->
        <el-button v-if="superAdmin" type="primary" style="float: right" @click="switching" icon="el-icon-sort">
          {{ switchName }}
        </el-button>
      </el-card>
      <!--    顶部搜索栏止-->

      <el-card style="margin-top: 20px">
        <!--      用户表格-->
        <el-table stripe v-show="switchName === '用户'" :data="userList" style="width: 100%">
          <el-table-column prop="No" label="序号" width="80" align="center" header-align="center">
            <template slot-scope="scope">
              {{ (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="id" label="用户id" width="auto" align="center" header-align="center" />
          <el-table-column prop="sno" label="学号/职工号" width="auto" align="center" header-align="center" />
          <el-table-column prop="cid" label="学院" width="auto" align="center" header-align="center" />
          <el-table-column prop="username" label="用户名" width="auto" align="center" header-align="center" />
          <el-table-column prop="password" label="密码" width="auto" align="center" header-align="center" />
          <el-table-column prop="email" label="邮箱" width="auto" align="center" header-align="center" />

          <el-table-column label="操作" width="220px" align="center" header-align="center">
            <template #default="scope">
              <el-button icon="el-icon-edit" type="primary" size="small" @click="openEditUI(scope.row, '修改')">编辑</el-button>
              <el-button icon="el-icon-delete" type="danger" size="small" @click="delUser(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--      管理员表格-->
        <el-table stripe v-show="switchName === '管理员'" :data="adminList" style="width: 100%">
          <el-table-column prop="No" label="序号" width="80" align="center" header-align="center">
            <template slot-scope="scope">
              {{ (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="id" label="管理员ID" width="auto" align="center" header-align="center" />
          <el-table-column prop="username" label="用户名" width="auto" align="center" header-align="center" />
          <el-table-column prop="cid" label="学院" width="auto" align="center" header-align="center" />
          <el-table-column prop="email" label="邮箱" width="auto" align="center" header-align="center" />
          <el-table-column prop="password" label="密码" width="auto" align="center" header-align="center" />
          <el-table-column label="操作" width="400px" align="center" header-align="center" fixed="right">
            <template slot-scope="scope">
              <el-button icon="el-icon-setting" type="primary" size="small" @click="assignRole(scope.row)">分配角色</el-button>
              <el-button icon="el-icon-edit" type="primary" size="small" @click="openEditUI(scope.row, '修改')">修改</el-button>
              <el-button icon="el-icon-delete" type="danger" size="small" @click="delAdmin(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--      分页器和页码选择器-->
        <el-pagination
          :current-page="searchModel.pageNo"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="searchModel.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 15px"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>

      <!--    弹窗，弹窗中显示的内容动态改变，改变的逻辑在openEditUI函数中。调用openEditUI即可显示弹窗-->
      <el-dialog :visible.sync="dialogFormVisible" :title="title" center @close="closeEditUI">
        <el-form :model="userForm">
          <el-form-item label="学号" label-width="100px" v-if="title === '修改用户'">
            <el-input v-model="userForm.sno" autocomplete="off" placeholder="请输入学号" />
          </el-form-item>
          <el-form-item label="用户名" label-width="100px" v-if="title === '修改用户' || title === '修改管理员' || title === '新增管理员'">
            <el-input v-model="userForm.username" autocomplete="off" placeholder="用户名" />
          </el-form-item>
          <el-form-item label="邮箱" label-width="100px" v-if="title === '修改用户' || title === '修改管理员' || title === '新增管理员'">
            <el-input v-model="userForm.email" autocomplete="off" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="学院" label-width="100px" v-if="title === '修改用户' || title === '修改管理员' || title === '新增管理员'">
            <el-input v-model="userForm.cid" autocomplete="off" placeholder="请输入学院名称" />
          </el-form-item>
          <el-form-item label="密码" label-width="100px" v-if="title === '修改用户' || title === '修改管理员' || title === '新增管理员'">
            <el-input v-model="userForm.password" autocomplete="off" placeholder="请输入密码" />
          </el-form-item>

          <!--        用于角色选择的复选框-->
          <!-- <el-form-item label="角色" label-width="100px" v-if="title === '修改管理员权限' || title === '新增管理员'">
          <template>
            <el-scrollbar>
              <div style="height: 200px">
                <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">校级管理员</el-checkbox>
                <el-checkbox-group
                  v-model="checkedRoles"
                  @change="handleCheckedRolesChange"
                  style="display: flex; flex-direction: column; margin-left: 10px; margin-top: 5px"
                >
                  <el-checkbox v-for="role in roles" :key="role" :label="role">{{ role }}</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-scrollbar>
          </template>
        </el-form-item> -->
          <el-form-item>
            <!-- 弹窗底部两个按钮-->
            <span class="dialog-footer">
              <el-button type="primary" v-show="title === '修改用户'" @click="updateUser(userForm)">确定</el-button>
              <el-button type="primary" v-show="title === '修改管理员'" @click="updateAdmin(userForm)">确定</el-button>
              <el-button type="primary" v-show="title === '新增管理员'" @click="addAdmin(userForm)">确定</el-button>
              <el-button @click="dialogFormVisible = false">取消</el-button>
            </span>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 分配角色窗口 -->
      <el-dialog :title="assignDialog.title" center :visible.sync="assignDialog.visible" @Close="onAssignClose">
        <!-- 分配角色数据列表 -->
        <el-table
          ref="assignRoleTable"
          :data="assignRoleList"
          stripe
          style="width: 100%; margin-bottom: 10px"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="role" label="角色名称"></el-table-column>
        </el-table>
        <!-- 分页工具栏 -->
        <el-pagination
          :current-page.sync="roleVo.pageNo"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="roleVo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="roleVo.total"
          style="margin-top: 15px"
          @size-change="assignSizeChange"
          @current-change="assignCurrentChange"
        />

        <div style="text-align: right; margin-top: 20px">
          <el-button type="primary" @click="saveUserRole()">确定</el-button>
          <el-button @click="assignDialog.visible = false">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </el-main>
</template>
  
  <script>
import userApi from '@/api/userManager'
import adminApi from '@/api/adminManager'
import { getToken } from '@/utils/auth'

export default {
  name: 'User',
  data() {
    return {
      title: '新增用户',
      dialogFormVisible: false,

      superAdmin: true,

      switchName: '用户',

      total: 0,
      searchModel: {
        userName: '',
        phone: '',
        pageNo: 1,
        pageSize: 10,
      },
      // 用户列表，用于存储普通用户的信息
      userList: [],
      // 管理员列表，用于存储管理员的信息
      adminList: [],
      // 临时存储用户/管理员信息，同时也是弹窗中输入框的值。该对象应为普通用户与管理员属性的并集
      userForm: {},

      //   checkAll: false,
      //   isIndeterminate: false,
      //   checkedRoles: [],
      //   roles: ['计算机与软件学院管理员', '。。。', '1', '2', '3', '4', '5'],

      //分配角色窗口属性
      assignDialog: {
        title: '分配角色',
        visible: false,
      },
      //角色对象
      roleVo: {
        pageNo: 1,
        pageSize: 10,
        userId: '',
        total: 0,
      },

      assignRoleList: [],

      SelectedIds: [],
      selectedUserId: '',
    }
  },
  methods: {
    // 用于处理分页器的改变
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize
      if (this.switchName === '用户') {
        this.getUserList()
      } else {
        this.getAdminList()
      }
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo
      if (this.switchName === '用户') {
        this.getUserList()
      } else if (this.switchName === '管理员') {
        this.getAdminList()
      }
    },

    //获取用户列表
    getUserList() {
      userApi
        .getUserList({
          token: getToken(),
          pageNo: this.searchModel.pageNo,
          pageSize: this.searchModel.pageSize,
        })
        .then((response) => {
          this.userList = response.data.rows
          this.total = response.data.total
        })
    },

    //获取管理员列表
    getAdminList() {
      this.searchModel.pageNo = 1
      this.total = 0
      adminApi
        .getAdminList({
          pageNo: this.searchModel.pageNo,
          pageSize: this.searchModel.pageSize,
        })
        .then((response) => {
          this.adminList = response.e.records
          this.total = response.e.total
        })
    },

    //修改用户
    updateUser(userData) {
      console.log(userData)
      userApi.updateUser({ user: userData }).then((response) => {
        this.$message.success('修改成功')
        this.dialogFormVisible = false
        this.getUserList()
      })
    },

    //修改管理员
    updateAdmin(userData) {
      adminApi.updateAdmin({ user: userData }).then((response) => {
        this.$message.success('修改成功')
        this.dialogFormVisible = false
        this.getAdminList()
      })
    },

    //删除用户
    delUser(id) {
      this.$confirm('此操作将删除该用户，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        userApi.delUser({ userId: id }).then((response) => {
          this.$message.success('删除成功')
          this.getUserList()
        })
      })
    },
    //删除管理员
    delAdmin(id) {
      this.$confirm('此操作将删除该管理员，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        adminApi.delAdmin({ id: id }).then((response) => {
          this.$message.success('删除成功')
          this.getAdminList()
        })
      })
    },

    //新增管理员
    addAdmin(userData) {
      adminApi.addAdmin({ admin: userData }).then((reponse) => {
        this.$message.success('新增成功')
        this.getAdminList()
      })
    },

    // 切换用户与管理员
    switching() {
      if (this.switchName === '用户') {
        this.getAdminList()
        this.switchName = '管理员'
        this.searchModel.pageNo = 1
        this.searchModel.pagesize = 10
      } else {
        this.getUserList()
        this.switchName = '用户'
        this.searchModel.pageNo = 1
        this.searchModel.pagesize = 10
      }
    },

    // 弹窗初始化
    openEditUI(val, type) {
      if (this.switchName === '用户') {
        if (type !== null) {
          this.title = '修改用户'
          this.userForm = Object.assign({}, val)
        }
      } else if (type === '授权') {
        this.title = '修改管理员权限'
      } else if (this.switchName === '管理员') {
        if (type != null) {
          this.title = '修改管理员'
          this.userForm = Object.assign({}, val)
        } else {
          this.title = '新增管理员'
        }
      }
      this.dialogFormVisible = true
    },

    // 弹窗关闭后的操作
    closeEditUI() {
      this.dialogFormVisible = false
      this.userForm = {
        No: '',
        sno: '',
        name: '',
        id: '',
        pwd: '',
        college: '',
        role: '',
      }
    },

    //处理复选框的改变
    handleCheckAllChange(val) {
      this.checkedRoles = val ? this.roles : []
      this.isIndeterminate = false
    },
    handleCheckedRolesChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.roles.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length
    },

    //打开分配角色
    assignRole(row) {
      this.SelectedIds = []

      this.selectedUserId = row.id

      this.assignDialog.visible = true
      this.assignDialog.title = '给【' + row.username + '】分配角色'
      this.getAssignRoleList()

      let params = { id: row.id }
      adminApi.getRoleIdByUserId(params).then((response) => {
        if (response.e) {
          this.selectedIds = response.e
          this.selectedIds.forEach((key) => {
            this.assignRoleList.forEach((item) => {
              if (item.id === key) {
                this.$refs.assignRoleTable.toggleRowSelection(item, true)
              }
            })
          })
        }
      })
    },

    //获取角色列表
    getAssignRoleList(pageNo = 1, pageSize = 10) {
      this.roleVo.userId = this.$store.getters.userId
      this.roleVo.pageNo = pageNo
      this.roleVo.pageSize = pageSize

      adminApi.getAssignRoleList(this.roleVo).then((response) => {
        this.assignRoleList = response.e.records
        this.roleVo.total = response.e.total
      })
    },

    //
    saveUserRole() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请选择要分配的角色!')
        return
      }
      let params = { userid: this.selectedUserId, list: this.selectedIds }
      adminApi.saveUserRole(params).then((response) => {
        this.$message.success(response.message)
        this.assignDialog.visible = false
      })
    },

    //分配角色窗口
    onAssignClose() {
      this.assignDialog.visible = false
    },
    onAssignConfirm() {
      this.assignDialog.visible = false
    },
    assignSizeChange(size) {
      this.roleVo.pagesize = size
      this.getAssignRoleList(this.roleVo.pageNo, size)
    },
    assignCurrentChange(page) {
      this.roleVo.pageNo = page
      this.getAssignRoleList(page, this.roleVo.pagesize)
    },

    //点击多选框时触发事件
    handleSelectionChange(rows) {
      let roleIds = []
      for (let i = 0; i < rows.length; i++) {
        roleIds.push(rows[i].id)
      }
      this.selectedIds = roleIds
    },
  },
  //窗口初始化做一次查询
  created() {
    this.getUserList()
  },
}
</script>
  
  <style scoped>
#search .el-input {
  width: 200px;
  margin-right: 10px;
}
.el-button {
  margin-right: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-footer-right {
  display: flex;
  justify-content: right;
  align-items: right;
}
.el-dialog .el-input {
  width: 80%;
}
</style>
  